import evil from '@/common/util/evil';
import tool from '@/common/util/tool';

const timespan = time => {
  var str = '';
  var now = new Date();
  if (typeof time === 'string') {
    time = new Date(Date.parse(time));
  }
  var span = now - time;
  var minutes = (span / 1000).toFixed(0);
  if (minutes < -60 * 60 * 24 * 30) {
    str = (-minutes / (60 * 60 * 24 * 30)).toFixed(0) + '月';
  } else if (minutes < -60 * 60 * 24) {
    str = (-minutes / (60 * 60 * 24)).toFixed(0) + '天';
  } else if (minutes < 60 * 60) str = (minutes / 60).toFixed(0) + '分钟前';
  else if (minutes < 60 * 60 * 24) {
    if (
      (minutes / (60 * 60)).toFixed(0) >= 24 &&
      (minutes / (60 * 60)).toFixed(0) <= 48
    ) {
      str = '昨天';
    } else {
      str = (minutes / (60 * 60)).toFixed(0) + '小时前';
    }
  } else if (minutes < 60 * 60 * 24 * 30) {
    str = (minutes / (60 * 60 * 24)).toFixed(0) + '天前';
  } else if (minutes < 60 * 60 * 24 * 365) {
    str = (minutes / (60 * 60 * 24 * 30)).toFixed(0) + '月前';
  } else {
    str = (minutes / (60 * 60 * 24 * 365)).toFixed(0) + '年前';
  }
  return str;
};

const dateTimeToDate = time => {
  if (!time) return '-';
  var date = new Date(time);
  var year = date.getFullYear();
  var month =
    date.getMonth() + 1 < 10
      ? '0' + (date.getMonth() + 1)
      : date.getMonth() + 1;
  var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
  return year + '-' + month + '-' + day;
};

const dateTimeToYearMonth = time => {
  if (!time) return '-';
  var date = new Date(time);
  var year = date.getFullYear();
  var month =
    date.getMonth() + 1 < 10
      ? '0' + (date.getMonth() + 1)
      : date.getMonth() + 1;
  return year + '-' + month;
};

const dateTimeToChineseDate = time => {
  if (!time) return '-';
  var date = new Date(time);
  var year = date.getFullYear();
  var month = date.getMonth() + 1;
  return year + '年' + month + '月';
};

const week = time => {
  if (time) time = new Date(time);
  var str = '日一二三四五六';
  str = '星期' + str.substr(time.getDay(), 1);
  return str;
};

const join = (list, propertyName) => {
  var arr = [];
  if (!list) return list;
  for (var i = 0; i < list.length; i++) arr.push(list[i][propertyName]);
  return arr.join(',');
};

const toDate = (input, fmt) => {
  return tool.toDate(input, fmt);
};

const substr = (string, start, length, usetail) => {
  var newString = '';
  var prefix = '';
  var suffix = '';
  if (typeof string === 'string') {
    newString = string.substr(start, length);
    // 结尾的省略号
    var idx = string.indexOf(newString);
    if (newString.length < string.substr(idx).length) {
      suffix = '...';
    }
    // 开头的省略号
    if (start < 0 && start > -string.length) {
      prefix = '...';
    }
    // 是否关闭了“添加省略号功能”
    if (!usetail) prefix = suffix = '';
    // 结果
    newString = prefix + newString + suffix;
  }
  return newString;
};

const replace = (string, regexp, replacement) => {
  var reg;
  try {
    reg = evil.evil(regexp);
  } catch (e) {
    reg = regexp;
  }
  var newString = '';
  if (typeof string === 'string') {
    newString = string.replace(reg, replacement);
  }
  return newString;
};

const trim = string => {
  return typeof string === 'string' ? string.replace(/(^\s*)|(\s*$)/g, '') : '';
};

const yearToChineseCharacters = year => {
  if (typeof year !== 'undefined') {
    var cn = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
    var s = [];
    var YY = year.toString();
    for (var i = 0; i < YY.length; i++) {
      if (cn[YY.charAt(i)]) s.push(cn[YY.charAt(i)]);
      else s.push(YY.charAt(i));
    }
    return s.join('');
  }
};

const monthToChineseCharacters = month => {
  if (typeof month !== 'undefined') {
    var cn = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
    var s = [];
    var MM = month;
    if (MM < 10) s.push(cn[MM]);
    else s.push('拾' + cn[MM % 10]);
    return s.join('');
  }
};

const dayToChineseCharacters = indate => {
  if (typeof indate !== 'undefined') {
    var cn = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
    var s = '';

    var indateSting = indate.toString();
    if (indate < 10) {
      s = cn[indateSting];
    } else {
      for (var i = 0; i < 1; i++) {
        if (indate >= 10 && indate < 20) {
          if (cn[indateSting.charAt(i + 1)]) {
            s = '拾';
            if (indateSting.charAt(i + 1) !== '0') {
              s = '拾' + cn[indateSting.charAt(i + 1)];
            }
          } else {
            s = indateSting.charAt(i) + indateSting.charAt(i + 1);
          }
        } else if (indate >= 20) {
          if (cn[indateSting.charAt(i + 1)]) {
            s = cn[indateSting.charAt(i)] + '拾';
            if (indateSting.charAt(i + 1) !== '0') {
              s =
                cn[indateSting.charAt(i)] +
                '拾' +
                cn[indateSting.charAt(i + 1)];
            }
          } else {
            s = indateSting.charAt(i) + indateSting.charAt(i + 1);
          }
        }
      }
    }
  }
  return s;
};
const moneyToChineseCharacters = input => {
  if (!/^(0|[1-9]\d*)(\.\d+)?$/.test(input)) return '数据非法';
  var unit = '千百拾亿千百拾万千百拾元角分';
  var str = '';
  input += '00';
  var p = input.indexOf('.');
  if (p >= 0) input = input.substring(0, p) + input.substr(p + 1, 2);
  unit = unit.substr(unit.length - input.length);
  for (var i = 0; i < input.length; i++) {
    str += '零壹贰叁肆伍陆柒捌玖'.charAt(input.charAt(i)) + unit.charAt(i);
  }
  return str
    .replace(/零(千|百|拾|角)/g, '零')
    .replace(/(零)+/g, '零')
    .replace(/零(万|亿|元)/g, '$1')
    .replace(/(亿)万|壹(拾)/g, '$1$2')
    .replace(/^元零?|零分/g, '')
    .replace(/元$/g, '元整');
};

const int = val => {
  // 强制转换为非NAN的数值
  val = parseInt(val);
  return isNaN(val) ? 0 : val;
};

// 通过值查找属性名
const findKey = (value, obj, compare = (a, b) => a === b) => {
  return Object.keys(obj).find(k => compare(obj[k], value));
};

// 数字保留小数
const toFixed = (value = 0.00, number = 2) => {
  value = parseFloat(value);
  if (!value) value = 0;
  return value.toFixed(number);
};

// 数字转为 ***
const hideMoney = money => {
	let userInfo = uni.getStorageSync('userInfo');
	if (userInfo.status != 3) 
		return money.toString().replace(/\d/g,'*');
	else return money;
};

// 从html字符串中提取文字
const takeText = html => {
  return tool.takeText(html);
};

export default {
  install(Vue) {
    Vue.filter('timespan', timespan);
    Vue.filter('week', week);
    Vue.filter('join', join);
    Vue.filter('toDate', toDate);
    Vue.filter('substr', substr);
    Vue.filter('replace', replace);
    Vue.filter('trim', trim);
    Vue.filter('yearToChineseCharacters', yearToChineseCharacters);
    Vue.filter('monthToChineseCharacters', monthToChineseCharacters);
    Vue.filter('dayToChineseCharacters', dayToChineseCharacters);
    Vue.filter('moneyToChineseCharacters', moneyToChineseCharacters);
    Vue.filter('dateTimeToDate', dateTimeToDate);
    Vue.filter('dateTimeToChineseDate', dateTimeToChineseDate);
    Vue.filter('dateTimeToYearMonth', dateTimeToYearMonth);
    Vue.filter('int', int);
    Vue.filter('toFixed', toFixed);
    Vue.filter('hideMoney', hideMoney);
    Vue.filter('findKey', findKey);
    Vue.filter('takeText', takeText);
  }
};
